﻿
CREATE  PROCEDURE [dbo].[resuma_InitializareTotalPontaj]
		@CodUnitate smallint,
        @Anul smallint,
        @Luna smallint
AS

delete FROM  AngajatiPontaj WHERE [Luna]=@Luna AND @Anul=@Anul AND [IDPersoana] IN (SELECT IDPersoana FROm [Persoane] WHERE [CodUnitate]=@CodUnitate)
delete AngajatiBoli WHERE [Luna]=@Luna AND @Anul=@Anul AND [IDPersoana] IN (SELECT IDPersoana FROm [Persoane] WHERE [CodUnitate]=@CodUnitate)

declare @ore_lucr Integer
DECLARE @IDPersoana int 
DECLARE @IDPersonalAngajat int
DECLARE	@norma integer
DECLARE	@norma_redusa integer

SET @ore_lucr = 0 -- (select ore_lucr  from seif)
-- initializez luna completa si la muncitori si la tesa

Declare crsAngajati Scroll Cursor for
Select Ps.IdPersoana, AngS.IDAngajatSalarizare
From Persoane Ps JOIN  AngajatiSalarizare AngS ON Ps.IDPersoana = AngS.IDPersoana
Where 
    Ps.CodUnitate=@CodUnitate AND
	YEAR(AngS.DeLaData)*100+MONTH(AngS.DeLaData)<=@Anul*100+@luna 
	AND (AngS.PanaLaData IS NULL OR @Anul*100+@Luna<=YEAR(AngS.PanaLaData)*100+MONTH(AngS.PanaLaData))
	AND (Ps.DataPlecarii IS NULL OR @Anul*100+@Luna<=YEAR(Ps.DataPlecarii)*100+MONTH(Ps.DataPlecarii))
	and AngS.Salar>0 

Open crsAngajati 

Fetch First from crsAngajati Into @IDPersoana, @IDPersonalAngajat

While @@fetch_status = 0
    Begin
                -- initializez pontajele angajatilor
                Exec resuma_InitializarePontaj @IDPersoana, @IDPersonalAngajat,1,@Luna,@Anul
				IF @@ERROR <>0
					GOTO EROARE
                Fetch Next from crsAngajati Into @IDPersoana, @IDPersonalAngajat
    End

Close crsAngajati
Deallocate crsAngajati

GOTO Gata
EROARE:
	RAISERROR ('Eroare la initializarea tuturor pontajelor!',16,-1)
	GOTO Gata
EROARE1:
	RAISERROR ('Nu a fost definit numarul de zile din luna',16,-1)	
	GOTO Gata
Gata: